<?php
namespace app\index\controller;
use think\Session;
use think\Controller;
use think\Exception;
use app\index\model\base;
use app\index\model\published_seismic_database;

class pubear extends Controller 
{


    public function baseInfo()
    {
        //网站截图目录初试化 start
        
        date_default_timezone_set('PRC');
        //$addtime=date("YmdHis",time());
        // mkdir('./public/images/autoExport/'.$addtime);
        // mkdir('./public/images/autoExport/'.$addtime.'/climateInfo');
        // mkdir('./public/images/autoExport/'.$addtime.'/disasterInfo');
        // mkdir('./public/images/autoExport/'.$addtime.'/earthquakeInfo');
        // mkdir('./public/images/autoExport/'.$addtime.'/economicInfo');
        // mkdir('./public/images/autoExport/'.$addtime.'/environmentInfo');
        // mkdir('./public/images/autoExport/'.$addtime.'/peopleInfo');
        // mkdir('./public/images/autoExport/'.$addtime.'/threeDimension');
        // mkdir('./public/images/autoExport/'.$addtime.'/twoDimension');
        //该session用来存储当前发震截图文件夹名称  
        // $_SESSION['timepath'] = $addtime;
        //网站截图目录初试化 end     
        /*post值应全为float*/
        
        //有改动
        $street=$_POST['street']; //街道名称
        $district=$_POST['district'];//县名称
        $EQTTIME=$_POST['time'];//发震时间
        $LONGTITUDE=$_POST['longtitude'];//经度
        $LATITUDE=$_POST['latitude'];//纬度
        $MAGNITUDE=$_POST['magnitude'];//震级
        $DEPTH=$_POST['depth'];//震源深度
        $CITY=$_POST['city'];//城市名称
        $RANGE='100';
        $province=$_POST['province'];//省名称
        $Intensity=$_POST['Intensity'];
        return $this->pubEQ($street,$district,$EQTTIME,$LONGTITUDE,$LATITUDE,$MAGNITUDE,$DEPTH,$CITY,$RANGE,$province,$Intensity);
    }
        public function pubEQ($street,$district,$EQTTIME,$LONGTITUDE,$LATITUDE,$MAGNITUDE,$DEPTH,$CITY,$RANGE,$province,$Intensity)
        {
           
        

        $pythonres = $this->req_python($LONGTITUDE, $LATITUDE);
        //return $pythonres;
        //var_dump($pythonres);
        $pyGetName='';
        //if($pythonres && $pythonres['data']['name']) $pyGetName = $pythonres['data']['name'];
        $base = new base();
        $results=$base->baseInfo($district,$CITY,$province,$street,$pyGetName);
        //$results=$base->baseInfo($district,$CITY,$province,$street);
        //坤 修改的部分
        //return $results;
        //end
        // var_dump($district );
        // 判断是否传入县名
        // 判断一下最近的那个地区
        $Mindistance=999999;$i=0;$flag=0;
        foreach ($results as $value) {
            $d=sqrt(pow($value['longtitude']-$LONGTITUDE,2)+pow($value['latitude']-$LATITUDE,2));
            if($Mindistance>$d){
                $Mindistance=$d;
                $flag=$i;
            }
            $i++;
        }
        $ischeck = 0;
        $pubEar = new published_seismic_database();
        
        if($results)
        {
            //$pubEar->updateEqtInfo();
            $OBJECTID = $results[$flag]['OBJECTID'];
            $x_longtitude = $results[$flag]['longtitude'];
            $x_latitude = $results[$flag]['latitude'];
            $GB_CODE = $results[$flag]['GB_CODE'];
            $name = $results[$flag]['name'];
            $abbreviation = $results[$flag]['abbreviation'];
            $city = $results[$flag]['city'];
            $province = $results[$flag]['province'];
            $tel = $results[$flag]['tel'];
            $remark = $results[$flag]['remark'];
            $abvProvince = $results[$flag]['abvProvince'];
            $fullName = $results[$flag]['fullName'];
            $abbreviationThree = $results[$flag]['abbreviationThree'];
            $POP_ALL = $results[$flag]['POP_ALL'];
            $POP_COUNTRYSIDE = $results[$flag]['POP_COUNTRYSIDE'];
            $POP_TOWN = $results[$flag]['POP_TOWN'];
            $GDP = $results[$flag]['GDP'];
            $FST_INDUSTRY = $results[$flag]['FST_INDUSTRY'];
            $SND_INDUSTRY = $results[$flag]['SND_INDUSTRY'];
            $TRD_INDUSTRY = $results[$flag]['TRD_INDUSTRY'];
            $townNum = $results[$flag]['townNum'];
            $villageNum = $results[$flag]['villageNum'];
            $climate = $results[$flag]['climate'];
            $area = $results[$flag]['area'];
            if($pythonres&&$pythonres['min']){
                $altitudeL = floor($pythonres['min']);
                $altitudeAverage = floor($pythonres['mean']);
                $altitudeH = floor($pythonres['max']);
            }else{
                $altitudeL = floor($results[$flag]['altitudeL']);
                $altitudeH =floor( $results[$flag]['altitudeH']);
                $altitudeAverage = floor($results[$flag]['altitudeAverage']);
            }
            $altitudeLName = $results[$flag]['altitudeLName'];
            $altitudeHName = $results[$flag]['altitudeHName'];
            $topographic = $results[$flag]['topographic'];
            $villageAverIncom = $results[$flag]['villageAverIncom'];
            $urbanAverIncome = $results[$flag]['urbanAverIncome'];
            $Population = $results[$flag]['Population'];
            $Economics = $results[$flag]['Economics'];

            //苏苏改动
            $ID = md5(time() . mt_rand(1,1000000));
            $params = array(
                'ID' => $ID,
                'EQTTIME' => $EQTTIME,
                'LONGITUDE' => $LONGTITUDE,
                'LATITUDE' => $LATITUDE,
                'MAGNITUDE' => $MAGNITUDE,
                'DEPTH' => $DEPTH,
                'Intensity' => $Intensity,
                'EQTRANGE' => $RANGE,
                'OBJECTID' => $OBJECTID,
                'x_longitude' => $x_longtitude,
                'x_latitude' => $x_latitude,
                'GB_CODE' => $GB_CODE,
                'eqtname' => $name,
                'abbreviation' => $abbreviation,
                'city' => $city,
                'province' => $province,
                'tel' => $tel,
                'remark' => $remark,
                'abvProvince' => $abvProvince,
                'fullName' => $fullName,
                'abbreviationThree' => $abbreviationThree,
                'POP_ALL' => $POP_ALL,
                'POP_COUNTRYSIDE' => $POP_COUNTRYSIDE,
                'POP_TOWN' => $POP_TOWN,
                'GDP' => $GDP,
                'FST_INDUSTRY' => $FST_INDUSTRY,
                'SND_INDUSTRY' => $SND_INDUSTRY,
                'TRD_INDUSTRY' => $TRD_INDUSTRY,
                'townNum' => $townNum,
                'villageNum' => $villageNum,
                'climate' => $climate,
                'area' => $area,
                'altitudeL' => $altitudeL,
                'altitudeLName' => $altitudeLName,
                'altitudeH' => $altitudeH,
                'altitudeHName' => $altitudeHName,
                'altitudeAverage' => $altitudeAverage,
                'topographic' => $topographic,
                'villageAverIncom' => $villageAverIncom,
                'urbanAverIncome' => $urbanAverIncome,
                'Population' => $Population,
                'Economics' => $Economics
            );
           $insertid = $pubEar->eqtinferInfo($params);
           if($insertid) {
            //$_SESSION['equnique'] = $insertid;
            Session::set('equnique',$ID);
            $ischeck = 1;
           }
        }
        return $ischeck;
        //echo json_encode($ischeck,JSON_UNESCAPED_UNICODE);
    }



    public function req_python ($lng, $lat) {
        $url="http://10.5.160.121/api/data/get_district_elevation/";
        $result = $this->get($url, array('longitude' => $lng, 'latitude' => $lat,'format'=>'json'));
        return json_decode($result,true);
    }
    public function get( $url, $params=array()){
        //解决发布超时
        // $opts = array(
        //     'http'=>array(
        //         'method'=>"GET"
        //     )
        // );
        // $url .= empty($params)?"":"?".http_build_query($params);
        // $context = stream_context_create($opts);
        //         try{
        //     $result =  file_get_contents($url,false,$context);    
        // }catch(Exception $e){
        //     $result = '';
        // }
        //$result =  file_get_contents($url,false,$context);
        // return $result;
        return "";
    }
    public function returnHistEart()
    {
        $lon=$_SESSION['longtitude'];
        $lat=$_SESSION['latitude'];
        $dis=1;
        $results=$this->PubEarthquake_Model->searchEartquake($lat,$lon,$dis);
        echo json_encode($results,JSON_UNESCAPED_UNICODE);
  
    }

    public function OPenSocket(){
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        $connection = socket_connect($socket, '10.5.160.121', 7080);
        echo  "Client send success \n";
        $this->login($socket);
        while ($out = socket_read($socket, 8,PHP_BINARY_READ)) {
            $response=$this->handleRespon($socket,$out);
            //var_dump($response);
            $Mode = $response->Head->Mode;
            //var_dump($response);
            if($Mode=="Response"){
              if($response->Body->StatusCode==200){
                echo "****************login sucess****************\n";
                echo "****************start subScribe****************\n";
                $this->subScribe($socket);
              }
            }else if($Mode=="SubscribeResponse"){
              if($response->Body->StatusCode==200){
                echo "****************subScribe sucess****************\n";
                
              }
            }else if($Mode=="Publish"){
              if($response->Body->Node=="earthquake.trigger"){
                $Parameters = $response->Body->Parameters;

                $EQTTIME=$Parameters->earthquake_time;//发震时间
                $LONGTITUDE=$Parameters->longitude;//经度
                $MAGNITUDE=$Parameters->magnitude;//震级
                $LATITUDE=$Parameters->latitude;//纬度
                $DEPTH=$Parameters->depth;//震源深度
                $Intensity=$DEPTH+2;
                $RANGE='100';
                //var_dump($city);
                $url='https://maps.google.cn/maps/api/geocode/json?latlng='.$LATITUDE.','.$LONGTITUDE.'&key=AIzaSyCbLfKHIBp1w36w3y04cK92v2uYNUuO9OU';
                //   var_dump($url);
                // var_dump($url);
       	        $ch = curl_init();
                $timeout = 5;
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch,CURLOPT_ENCODING ,'gzip');
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //跳过ssl认证；
                $file_contents = curl_exec($ch);
                //var_dump(curl_error($ch)); 
                curl_close($ch);
                if($file_contents->status=='OK'){
                    $res = $file_contents ->results[0];
                    $street=$res->address_components[0]->long_name;
                    $district = $res ->address_components[1]->long_name;
                    $CITY = $res ->address_components[2]->long_name;
                    $province = $res ->address_components[3] ->long_name;
                    $this->pubEQ($street,$district,$EQTTIME,$LONGTITUDE,$LATITUDE,$MAGNITUDE,$DEPTH,$CITY,$RANGE,$province,$Intensity);
                    
                }else{
                    echo 'googel key 过期';
                }

                //$street=$_POST['street']; //街道名称
                //$district=$_POST['district'];//县名称
                //$CITY=$_POST['city'];//城市名称
                
                //$province=$_POST['province'];//省名称
                echo '接收到地震推送';
              }
              
            
          }else{
            echo "get data file";
          }
    
        }    
    }

    private function handleRespon($socket,$out){
        $response = null;
        $out=unpack('J',$out);
          if($out[1]==97114859022255){
            $out = socket_read($socket,4,PHP_BINARY_READ);
            $out = unpack('N',$out);
            $out = socket_read($socket,$out[1],PHP_BINARY_READ);
            $response =  json_decode ($out);
            
        }
        return $response;
    }

    private function login($socket){
        $send_data = json_encode(["Head"=>["TransactionId"=>1,"Mode"=>"Request"],"Body"=>[   "RequestId"=>100,"Method"=>"developer.login","Parameters"=>["app_id"=>"ss61d15fb2","app_key"=>"61d1623251d411e88c410cda411dcf6a"]]]);
        $len = strlen($send_data);
        $head =$this->getHead($len);
        socket_write($socket,$head.$send_data,12+$len);
    }

    private function getHead($len)
    {
      $aa =0X585350ACA7AF;
      $pack= pack('J',$aa);
      $num=pack('N',$len);
      return $pack.$num;
      # code...
    }

    private function subScribe($socket)
    {
      $data=array(
                "Head"=>array(
                  "TransactionId"=>2,
                  "Mode"=>"Subscribe"
                ),
                "Body"=>array(
                  "Node"=>"earthquake.trigger"
                )
      );
      $dataJ=json_encode($data);
      $len=strlen($dataJ);
      $head=$this->getHead($len);
      socket_write($socket,$head.$dataJ,12+$len);
    }

    // public function getElevation($lon,$lat){
    //     $url="http://10.5.160.121/api/data/get_elevation/?format=json&lon=$lon&lat=$lat";
    //     var_dump($url);
    //     $ch = curl_init();
    //     $timeout = 5;
    //     curl_setopt($ch, CURLOPT_URL, $url);
    //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //     curl_setopt($ch,CURLOPT_ENCODING ,'gzip');
    //     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    //     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //跳过ssl认证；
    //     $file_contents = curl_exec($ch);
    //     curl_close($ch);
    //     var_dump($file_contents);
    // }


    public function aa(){
        return var_dump($url);
    }
}
